//
//  KVEmoticonModel.swift
//  KVEmoticon
//
//  Created by 李康卫 on 16/7/29.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit

class KVEmoticonModel: NSObject, NSCoding {
    ///文件目录名称
    var id: String
    ///图片名称
    var code: String? {
        didSet {
//            let scanner = NSScanner(string: code!)
//            
//            var result: UInt32 = 0
//            scanner.scanHexInt(&result)
//            
//            print(result)
//            
//            let str = "\(Character(UnicodeScalar(result)))"
//            self.emoji = str
            // 扫描
            let sacnner = NSScanner(string: code!)
            
            var result: UInt32 = 0
            // UnsafeMutablePointer<UInt32>: 要一个UInt32类型的指针
            sacnner.scanHexInt(&result)
            
            let scalar = UnicodeScalar(result)
            
            let c = Character(scalar)
            
            // 转成emoji
            emoji = String(c)
        }
    }
    
    /// emoji图片
    var emoji: String?
   
    ///网络传输名称
    var chs: String?
    ///本地图片名
    var png: String? {
        didSet {
           iconPath = KVEmoticonModelManeger.sharedEmoticonManeger.packagePath! + "/" + id + "/" + png!
        }
    }
    
    ///图片路径
    var iconPath :String?
    //初始化字典转模型
    init(id: String,dic: [String: String]){
        self.id = id
       super.init()
        setValuesForKeysWithDictionary(dic)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        get {
            return "code:\(emoji) 包名：\(chs) 图片png\(png)"
        }
    }
//    解码
    required init?(coder aDecoder: NSCoder) {
        id = aDecoder.decodeObjectForKey("id") as! String
        code = aDecoder.decodeObjectForKey("code") as? String
        emoji = aDecoder.decodeObjectForKey("emoji") as? String
        chs = aDecoder.decodeObjectForKey("chs") as? String
        png = aDecoder.decodeObjectForKey("png") as? String
        iconPath = aDecoder.decodeObjectForKey("iconPath") as? String
        if png != nil {
            iconPath = KVEmoticonModelManeger.sharedEmoticonManeger.packagePath! + "/" + id + "/" + png!
        }
        
    }
    //编码
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(id, forKey: "id")
        aCoder.encodeObject(code, forKey: "code")
        aCoder.encodeObject(emoji, forKey: "emoji")
        aCoder.encodeObject(chs, forKey: "chs")
        aCoder.encodeObject(png, forKey: "png")
        aCoder.encodeObject(iconPath, forKey: "iconPath")
        
    }
}
